<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-position="left" style="margin: 20px;" :rules="rules">
      <el-row>
        <el-col :span="4">
          <el-form-item>
            <el-radio v-model="form.type" label="1">年</el-radio>
            <el-radio v-model="form.type" label="2">月</el-radio>
            <el-radio v-model="form.type" label="3">日</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <template v-if="form.type=='1'">
            <el-form-item label="选择年份:" label-width="90px" prop="startYear">
              <el-date-picker
                v-model="startYear"
                placeholder="选择年份"
                type="year"
                value-format="yyyy"
                style="width: 98%;"
              />
            </el-form-item>
          </template>
          <template v-if="form.type=='2'">
            <el-form-item label="选择月份:" prop="endYear" label-width="90px">
              <el-date-picker
                v-model="endYear"
                placeholder="选择月份"
                type="month"
                style="width: 98%;"
                value-format="yyyy-MM"
              />
            </el-form-item>
          </template>
          <template v-if="form.type=='3'">
            <el-form-item label="选择日期:" prop="date" label-width="90px">
              <el-date-picker
                v-model="form.date"
                type="daterange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 98%;"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
          </template>
        </el-col>
        <el-col :span="5">
          <el-form-item label="选择部门:" prop="deptId" label-width="90px">
            <treeselect
              v-model="form.deptId"
              size="small"
              :options="depts"
              :load-options="loadDepts"
              placeholder="选择部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item>
            <el-button type="primary" style="margin-left: 20px; width: 100px;" @click="selectSaleReport()">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div style="margin: 20px;">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column label="VIP销售额">
          <template slot-scope="scope">
            <span>{{ scope.row.VIPCard /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="在线充值">
          <template slot-scope="scope">
            <span>{{ scope.row.OnlineAdd /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="选科">
          <template slot-scope="scope">
            <span>{{ scope.row.VIPSubject /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名师微课">
          <template slot-scope="scope">
            <span>{{ scope.row.Weike /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="志愿填报">
          <template slot-scope="scope">
            <span>{{ scope.row.ZhiYuan /100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名师课件">
          <template slot-scope="scope">
            <span>{{ scope.row.KeJian /100 }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="dashboard-editor-container" style="margin: 20px 0;">
      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">VIP销售额</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="VIPCard" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">在线充值</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="OnlineAdd" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">选科</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="KeJian" />
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">名师微课</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="Weike" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">名师课件</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="VIPSubject" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div style="position: relative;left: 42%; font-size: 18px;">志愿填报</div>
          <div class="chart-wrapper">
            <pie-chart :h-data="hDate" :v-data="ZhiYuan" />
          </div>
        </el-col>
      </el-row>
      <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
        <fold-bar-chart :fold-data="foldData" />
      </el-row>
    </div>
  </div>
</template>

<script>
import PieChart from '../../dashboard/PieChart'
import FoldBarChart from '../../dashboard/FoldBarChart'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { saleReport } from '@/api/report/report'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { mapGetters } from 'vuex'

export default {
  name: 'SaleReport',
  components: {
    PieChart, FoldBarChart, Treeselect
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  data() {
    const validEndYear = (rule, value, callback) => {
      if (this.endYear.length <= 0) {
        callback(new Error('请选择月份'))
      } else {
        callback()
      }
    }
    const validStartYear = (rule, value, callback) => {
      if (this.startYear.length <= 0) {
        callback(new Error('请选择年份'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        startYear: [
          { required: true, trigger: 'blur', validator: validStartYear }
        ],
        endYear: [
          { required: true, trigger: 'blur', validator: validEndYear }
        ],
        date: [
          { required: true, trigger: 'blur', message: '请选择时间' }
        ],
        deptId: [
          { required: true, trigger: 'blur', message: '请选择部门' }
        ]
      },
      hDate: [], foldData: [],
      KeJian: [], OnlineAdd: [], VIPCard: [], VIPSubject: [], Weike: [], ZhiYuan: [],
      depts: [],
      startYear: '2020',
      endYear: '',
      form: {
        date: '',
        type: '1',
        startTime: '',
        endTime: '',
        deptId: null
      },
      tableData: [],
      pickerMinDate: '',
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.pickerMinDate = minDate.getTime()
          if (maxDate) {
            this.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          if (this.pickerMinDate !== '') {
            const day30 = (30 - 1) * 24 * 3600 * 1000
            let maxTime = this.pickerMinDate + day30
            if (maxTime > new Date()) {
              maxTime = new Date()
            }
            return time.getTime() > maxTime
          }
          return time.getTime() > Date.now()
        }
      }
    }
  },
  mounted() {
    if (this.user.depts.length !== 0) {
      const depts = this.user.depts[0]
      this.form.deptId = depts.deptId
    } else {
      this.form.deptId = null
    }
  },
  created() {
    this.getDepts()
    this.getSupDepts(this.user.dept.id)
    this.loadFirst()
  },
  methods: {

    selectSaleReport() {
      if (parseInt(this.form.type) === 1) {
        this.form.startTime = this.startYear + '-01-01 00:00:00'
        this.form.endTime = this.startYear + '-12-31 23:59:59'
      }
      if (parseInt(this.form.type) === 2) {
        // 如果选择2020-02 则上传2020-02-01到2020-03-01
        var arr1 = this.endYear.split('-')
        var year = arr1[0]
        var month = arr1[1]
        var valueMonth = (parseInt(month) === 12) ? '01' : (parseInt(month) + 1)
        var valueStr = (parseInt(month) === 12) ? (parseInt(year) + 1 + '-' + valueMonth) : (parseInt(year) + '-' + valueMonth)
        this.form.startTime = this.endYear + '-01 00:00:00'
        this.form.endTime = valueStr + '-01 00:00:00'
      }
      if (parseInt(this.form.type) === 3) {
        this.form.startTime = this.form.date[0]
        this.form.endTime = this.form.date[1]
      }

      if (this.$refs['form']) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.request(this.form)
          }
        })
      }
    },
    loadFirst() {
      if (parseInt(this.form.type) === 1) {
        this.form.startTime = this.startYear + '-01-01 00:00:00'
        this.form.endTime = this.startYear + '-12-31 23:59:59'
      }
      this.request(this.form)
    },

    async request(params) {
      const res = await saleReport(params)
      const { KeJianInfo, OnlineAddInfo, VIPCardInfo, VIPSubjectInfo, WeikeInfo, ZhiYuanInfo } = res

      // 表格数据
      const arr = []
      arr.push(res.info)
      this.tableData = arr

      // 横坐标显示
      // this.hDate = KeJianInfo.map(obj => {
      //   return obj.date
      // })

      // 柱状图数据
      const foldArray = []
      KeJianInfo.forEach((v, i) => {
        const list = {
          name: '',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: []
        }
        var obj = {}
        var ResultArr_ = 'info'
        obj[ResultArr_ + i] = []
        for (var j in obj) {
          const a = obj[j]
          for (var k in res) {
            const info = res[k][i]
            if (typeof (info) === 'object') {
              a.push(info.dealAmount / 100)
              list.name = info.date
              list.data = a
            }
          }
        }
        foldArray.push(list)
        obj = null
      })
      this.foldData = foldArray

      // 饼图
      this.KeJian = KeJianInfo && this.handlweData(KeJianInfo)
      this.OnlineAdd = OnlineAddInfo && this.handlweData(OnlineAddInfo)
      this.VIPCard = VIPCardInfo && this.handlweData(VIPCardInfo)
      this.VIPSubject = VIPSubjectInfo && this.handlweData(VIPSubjectInfo)
      this.Weike = WeikeInfo && this.handlweData(WeikeInfo)
      this.ZhiYuan = ZhiYuanInfo && this.handlweData(ZhiYuanInfo)
    },

    // 处理饼图数据格式
    handlweData(array) {
      const values = []
      array.forEach(obj => {
        const list = {
          'name': '',
          'value': ''
        }
        list.name = obj.date
        list.value = obj.dealAmount / 100
        values.push(list)
      })
      return values
    },

    // 获取部门数据
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },

    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },

    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  // background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
